class Order < ApplicationRecord
    has_many :order_items,dependent: :destroy
    belongs_to :restaurant
    belongs_to :user
    before_validation :generate_order_number
    before_save :save_table_number
    validates :order_number,presence: true,uniqueness: true

    WAIT = 0
    SUCCESS = 1
    CANCEL = 2
    FINISH = 3

    ONLINE_PAY = 0
    OFFLINE_PAY = 1

    def label
        if self.status.to_i == WAIT
            "待商家确认"
        elsif self.status.to_i == SUCCESS
            "已成功支付"
        elsif self.status.to_i == CANCEL
            "已取消" 
        elsif self.status.to_i == FINISH
            "已完成"          
        end        
    end    

    def is_pay?
        if self.is_pay
            "已支付"
        else
            "待支付"
        end    
    end    


    def add_line_item_from_cart(cart)
        cart.order_items.each do |item|
            item.car_id = nil
            order_items << item
        end
    end

    def total_price
        order_items.to_a.sum{|item| item.total_price}
    end    

    def total_quantity
        order_items.to_a.sum{|item| item.quantity}
    end    

    def generate_order_number
        if self.order_number.blank?
            time = Time.now.to_i
            self.order_number = "#{time}-#{self.restaurant_id}-#{self.user_id}"
        end    
    end    

    def save_table_number
        if self.show_number.blank?
            self.show_number = Order.where(status: [WAIT,SUCCESS],restaurant_id: self.restaurant_id).count+1
        end    
    end    


end
